// pages/addAddress/addAddress.js
const app = getApp();
let Api = require('../../api/api.js');
Page({
    /**
     * 页面的初始数据
     */
    data: {
        tipText:'详细地址不能为空',
        showToast:false,
        areaText:'请选择',
        name:'',
        phone: '',
        detailAddress: '',
        setDefault:'',
        showPickerCityVal:false,
        addressid:'',
        openType:'add',
        ordernumber:'',
    }, 

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let self = this;
        if(options.type == 'add'){ // 点击添加地址按钮进入
            self.setData({
                openType:'add'
            })
        } else if (options.type == 'edit') { // 点击编辑按钮进入
            if (options.isdefault == 1){
                self.setData({
                    setDefault: options.isdefault,
                })
            }
            self.setData({
                addressid: options.addressid,
                name: options.name,
                phone: options.phone,
                areaText: options.area,
                detailAddress: options.detaile,
            })
        } else if (options.type == 'myOrder' || options.type == 'orderDetail') {// 我的订单页面进入
            self.setData({
                openType: options.type,
                // name: options.name,
                // phone: options.phone,
                // areaText: options.area,
                // detailAddress: options.detaile,
                ordernumber: options.ordernumber,
            })
            Api.get(app.globalData.mallDomain, {//18）我的订单列表
                doShowMyOrderList: 1,
                token: app.globalData.token,
                ordernumber: options.ordernumber,
                status:'1'
            }).then(res => {
                console.log(res)
                self.setData({
                    name: res.data.list[0].name,
                    phone: res.data.list[0].phone,
                    areaText: res.data.list[0].address.split(' ')[0],
                    detailAddress: res.data.list[0].address.split(' ')[res.data.list[0].address.split(' ').length - 1],
                })
            })
        }
    }, 
    /**
     * 保存
     */
    save: function () {
        let self = this;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];  //上一个页面
        //修改地址列表属性值
        if (self.data.name == '') { //验证收货人有没有填写
            self.setData({
                tipText: '请输入收货人',
                showToast: true,
            })
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            return;
        }
        if (self.data.phone == '') {//验证联系方式有没有填写
            self.setData({
                tipText: '请输入联系电话',
                showToast: true,
            })
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            return;
        }
        if (self.data.phone.match(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/) == null) {//验证手机号有没有填写正确
            self.setData({
                tipText: '请输入正确的11位手机号',
                showToast: true,
            })
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            return;
        }
        if (self.data.detailAddress == '') { //验证详细地址有没有填写
            self.setData({
                tipText: '请输入详细地址',
                showToast: true,
            })
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            return;
        }
        if (self.data.areaText == '请选择') { //验证所在区域有没有选择
            self.setData({
                tipText: '请选择所在区域',
                showToast: true,
            })
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            return;
        }
        if (self.data.openType == 'myOrder' || self.data.openType == 'orderDetail'){ //我的订单页面进入修改地址
            Api.get(app.globalData.mallDomain, {//20）修改地址
                doUpOrderAddress: 1,
                token: app.globalData.token,
                name: self.data.name,
                phone: self.data.phone,
                area: self.data.areaText,
                detail: self.data.detailAddress,
                ordernumber: self.data.ordernumber,
            }).then(res => {
                if (res.data.msg == '122'){
                    self.setData({
                        tipText: '修改成功',
                        showToast: true,
                    })
                     //修改订单详情页面的地址信息  未测试代码结果
                    if (self.data.openType == 'orderDetail'){
                        let name = "orderDetail[0].name";
                        let phone = "orderDetail[0].phone";
                        let address = "orderDetail[0].address";
                        prevPage.setData({
                            [name]: self.data.name,
                            [phone]: self.data.phone,
                            [address]: self.data.detailAddress,
                        })
                    }
                }
            })
        }else{ //添加或编辑地址
            Api.get(app.globalData.mallDomain, {//10）添加或者修改地址
                doAddOrUpdateAddress: 1,
                token: app.globalData.token,
                name: self.data.name,
                phone: self.data.phone,
                area: self.data.areaText,
                detaile: self.data.detailAddress,
                isdefault: self.data.setDefault,
                addressid: self.data.addressid,
            }).then(res => {
                console.log(res,'添加地址成功')
                if (res.data.msg == '109') {
                    self.setData({
                        tipText: '添加成功',
                        showToast: true,
                    })
                    //重置地址列表 
                    Api.get(app.globalData.mallDomain, { //地址列表展示接口
                        doShowAddressList: 1,
                        token: app.globalData.token,
                    }).then(res => {
                        if (res.data.msg == '108') {
                            let pages = getCurrentPages();
                            let prevPage = pages[pages.length - 2];  //上一个页面
                            let prevPage2 = pages[pages.length - 3];  //订单页面
                            let listData = [];
                            let defaultData = {};
                            res.data.list.forEach(ele => {
                                listData.push({
                                    addressid: ele.addressid,
                                    name: ele.name,
                                    phone: ele.phone,
                                    area: ele.area,
                                    detaile: ele.detaile,
                                    isdefault: ele.isdefault,
                                })
                            })
                            let haveDefault = false;
                            //默认地址放置在第一位
                            for (var i = 0; i < listData.length; i++) {
                                if (listData[i].isdefault == 1) {
                                    defaultData = listData[i];
                                    listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                                    listData.unshift(defaultData); // 再添加到第一个位置
                                    
                                    prevPage2.setData({
                                        name: listData[i].name,
                                        phone: listData[i].phone,
                                        area: listData[i].detaile,
                                        addressid: listData[i].addressid,
                                    })
                                    haveDefault = true;
                                }
                            }
                            prevPage.setData({
                                addressList: listData
                            })
                            if (haveDefault == false) {
                                prevPage2.setData({
                                    name: '',
                                    phone: '',
                                    area: '',
                                    addressid: '',
                                })
                            }
                        }
                    })
                }
            })
        }
        setTimeout(function () {
            self.setData({
                tipText: '',
                showToast: false
            })
            wx.navigateBack({
                delta: 1
            })
        }, 1000)
    },
    /**
     * 监听选择城市 点击背景，取消按钮，确认按钮传来的值
     */
    changeState :function(e){
        let self = this;
        if (e.detail != undefined && e.detail != null && e.detail != '' ){ //点击确定按钮
            self.setData({
                areaText: e.detail,
            })
        }
        self.setData({
            showPickerCityVal:false,
        })
    },
    /**
     * 选择地区 三级联动
     */
    selectArea: function () {
        let  self = this;
        self.setData({
            showPickerCityVal:true,
        })
    },
    /**
     * 设置默认地址
     */
    setDefault: function (e) {
        let self = this;
        if (self.data.setDefault == 1) {
            self.setData({
                setDefault: ''
            })
        }else{
            self.setData({
                setDefault: e.detail.value
            })
        }
    }, 
    /**
     * 获取输入联系电话
     */
    addPhone: function(e) {
        let self = this;
        self.setData({
            phone: e.detail.value.replace(/\s+/g, "")
        })
    },
    /**
     * 获取输入姓名
     */
    addName:function(e){
        let self = this;
        self.setData({
            name: e.detail.value.replace(/\s+/g, "")
        })
    },
    /**
     * 选择地区
     */
    bindTextAreaBlur: function (e) {
        let self = this;
        self.setData({
            detailAddress: e.detail.value.replace(/\s+/g, "")
        })
    },
})